package com.warom.sdg.repository;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


import com.warom.sdg.database.SdgDatabase;
import com.warom.sdg.model.PestDetectionEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

/**
 * 虫情检测数据仓库
 * 负责虫情检测数据的存储和查询
 */
public class PestDetectionRepository {
    private static final String TAG = "PestDetectionRepository";
    
    // 数据库
    private final SdgDatabase database;
    
    // 线程池，用于异步操作
    private final Executor executor;
    
    // 表名和列名使用SdgDatabase中的常量
    public static final String TABLE_NAME = SdgDatabase.TABLE_PEST_DETECTION;
    
    /**
     * 构造函数
     * @param context 上下文
     */
    public PestDetectionRepository(Context context) {
        this.database = SdgDatabase.getInstance(context);
        this.executor = Executors.newSingleThreadExecutor();
    }
    
    /**
     * 插入数据
     * @param entity 数据实体
     * @param successCallback 成功回调
     * @param errorCallback 错误回调
     */
    public void insert(PestDetectionEntity entity, Runnable successCallback, 
                      Consumer<String> errorCallback) {
        executor.execute(() -> {
            SQLiteDatabase db = null;
            try {
                db = database.getWritableDatabase();
                
                ContentValues values = new ContentValues();
                values.put(SdgDatabase.COLUMN_DEVICE_ID, entity.getDeviceId());
                values.put(SdgDatabase.COLUMN_PEST_TYPE, entity.getPestType());
                values.put(SdgDatabase.COLUMN_CONFIDENCE, entity.getConfidence());
                values.put(SdgDatabase.COLUMN_COUNT, entity.getCount());
                values.put(SdgDatabase.COLUMN_IMAGE_URL, entity.getImageUrl());
                values.put(SdgDatabase.COLUMN_TIMESTAMP, entity.getTimestamp());
                values.put(SdgDatabase.COLUMN_STATUS, entity.getStatus());
                
                long newRowId = db.insert(TABLE_NAME, null, values);
                
                if (newRowId != -1) {
                    Log.d(TAG, "数据插入成功，ID: " + newRowId);
                    entity.setId((int) newRowId);
                    if (successCallback != null) {
                        successCallback.run();
                    }
                } else {
                    String errorMsg = "数据插入失败";
                    Log.e(TAG, errorMsg);
                    if (errorCallback != null) {
                        errorCallback.accept(errorMsg);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "数据插入异常", e);
                if (errorCallback != null) {
                    errorCallback.accept(e.getMessage());
                }
            }
        });
    }
    
    /**
     * 批量插入数据
     * @param entities 数据实体列表
     * @param successCallback 成功回调
     * @param errorCallback 错误回调
     */
    public void insertBatch(List<PestDetectionEntity> entities, Runnable successCallback,
                          Consumer<String> errorCallback) {
        executor.execute(() -> {
            SQLiteDatabase db = null;
            try {
                db = database.getWritableDatabase();
                db.beginTransaction();
                
                for (PestDetectionEntity entity : entities) {
                    ContentValues values = new ContentValues();
                    values.put(SdgDatabase.COLUMN_DEVICE_ID, entity.getDeviceId());
                    values.put(SdgDatabase.COLUMN_PEST_TYPE, entity.getPestType());
                    values.put(SdgDatabase.COLUMN_CONFIDENCE, entity.getConfidence());
                    values.put(SdgDatabase.COLUMN_COUNT, entity.getCount());
                    values.put(SdgDatabase.COLUMN_IMAGE_URL, entity.getImageUrl());
                    values.put(SdgDatabase.COLUMN_TIMESTAMP, entity.getTimestamp());
                    values.put(SdgDatabase.COLUMN_STATUS, entity.getStatus());
                    
                    long newRowId = db.insert(TABLE_NAME, null, values);
                    if (newRowId != -1) {
                        entity.setId((int) newRowId);
                    }
                }
                
                db.setTransactionSuccessful();
                Log.d(TAG, "批量数据插入成功，数量: " + entities.size());
                
                if (successCallback != null) {
                    successCallback.run();
                }
            } catch (Exception e) {
                Log.e(TAG, "批量数据插入异常", e);
                if (errorCallback != null) {
                    errorCallback.accept(e.getMessage());
                }
            } finally {
                if (db != null && db.inTransaction()) {
                    db.endTransaction();
                }
            }
        });
    }
    
    /**
     * 获取指定设备的历史数据
     * @param deviceId 设备ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param limit 限制返回记录数
     * @param callback 结果回调
     * @param errorCallback 错误回调
     */
    public void getHistoryData(int deviceId, long startTime, long endTime, int limit,
                             Consumer<List<PestDetectionEntity>> callback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            SQLiteDatabase db = null;
            Cursor cursor = null;
            try {
                db = database.getReadableDatabase();
                
                String selection = SdgDatabase.COLUMN_DEVICE_ID + " = ? AND " +
                                  SdgDatabase.COLUMN_TIMESTAMP + " >= ? AND " +
                                  SdgDatabase.COLUMN_TIMESTAMP + " <= ?";
                                  
                String[] selectionArgs = {
                        String.valueOf(deviceId),
                        String.valueOf(startTime),
                        String.valueOf(endTime)
                };
                
                String sortOrder = SdgDatabase.COLUMN_TIMESTAMP + " DESC LIMIT " + limit;
                
                cursor = db.query(
                        TABLE_NAME,
                        null,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
                
                List<PestDetectionEntity> results = new ArrayList<>();
                
                while (cursor.moveToNext()) {
                    PestDetectionEntity entity = new PestDetectionEntity();
                    entity.setId(cursor.getInt(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_ID)));
                    entity.setDeviceId(cursor.getInt(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_DEVICE_ID)));
                    entity.setPestType(cursor.getString(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_PEST_TYPE)));
                    entity.setConfidence(cursor.getDouble(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_CONFIDENCE)));
                    entity.setCount(cursor.getInt(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_COUNT)));
                    entity.setImageUrl(cursor.getString(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_IMAGE_URL)));
                    entity.setTimestamp(cursor.getLong(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_TIMESTAMP)));
                    entity.setStatus(cursor.getString(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_STATUS)));
                    
                    results.add(entity);
                }
                
                Log.d(TAG, "查询到 " + results.size() + " 条历史数据");
                
                if (callback != null) {
                    callback.accept(results);
                }
            } catch (Exception e) {
                Log.e(TAG, "查询历史数据异常", e);
                if (errorCallback != null) {
                    errorCallback.accept(e.getMessage());
                }
            } finally {
                if (cursor != null && !cursor.isClosed()) {
                    cursor.close();
                }
            }
        });
    }
    
    /**
     * 获取所有设备的历史数据
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param limit 限制返回记录数
     * @param callback 结果回调
     * @param errorCallback 错误回调
     */
    public void getAllHistoryData(long startTime, long endTime, int limit,
                                Consumer<List<PestDetectionEntity>> callback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            SQLiteDatabase db = null;
            Cursor cursor = null;
            try {
                db = database.getReadableDatabase();
                
                String selection = SdgDatabase.COLUMN_TIMESTAMP + " >= ? AND " +
                                  SdgDatabase.COLUMN_TIMESTAMP + " <= ?";
                                  
                String[] selectionArgs = {
                        String.valueOf(startTime),
                        String.valueOf(endTime)
                };
                
                String sortOrder = SdgDatabase.COLUMN_TIMESTAMP + " DESC LIMIT " + limit;
                
                cursor = db.query(
                        TABLE_NAME,
                        null,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
                
                List<PestDetectionEntity> results = new ArrayList<>();
                
                while (cursor.moveToNext()) {
                    PestDetectionEntity entity = new PestDetectionEntity();
                    entity.setId(cursor.getInt(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_ID)));
                    entity.setDeviceId(cursor.getInt(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_DEVICE_ID)));
                    entity.setPestType(cursor.getString(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_PEST_TYPE)));
                    entity.setConfidence(cursor.getDouble(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_CONFIDENCE)));
                    entity.setCount(cursor.getInt(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_COUNT)));
                    entity.setImageUrl(cursor.getString(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_IMAGE_URL)));
                    entity.setTimestamp(cursor.getLong(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_TIMESTAMP)));
                    entity.setStatus(cursor.getString(cursor.getColumnIndexOrThrow(SdgDatabase.COLUMN_STATUS)));
                    
                    results.add(entity);
                }
                
                Log.d(TAG, "查询到所有设备 " + results.size() + " 条历史数据");
                
                if (callback != null) {
                    callback.accept(results);
                }
            } catch (Exception e) {
                Log.e(TAG, "查询所有设备历史数据异常", e);
                if (errorCallback != null) {
                    errorCallback.accept(e.getMessage());
                }
            } finally {
                if (cursor != null && !cursor.isClosed()) {
                    cursor.close();
                }
            }
        });
    }
    
    /**
     * 删除过期数据
     * @param beforeTime 删除此时间戳之前的数据
     * @param successCallback 成功回调
     * @param errorCallback 错误回调
     */
    public void deleteOldData(long beforeTime, Runnable successCallback,
                             Consumer<String> errorCallback) {
        executor.execute(() -> {
            SQLiteDatabase db = null;
            try {
                db = database.getWritableDatabase();
                
                String selection = SdgDatabase.COLUMN_TIMESTAMP + " < ?";
                String[] selectionArgs = { String.valueOf(beforeTime) };
                
                int deletedRows = db.delete(TABLE_NAME, selection, selectionArgs);
                
                Log.d(TAG, "删除了 " + deletedRows + " 条过期数据");
                
                if (successCallback != null) {
                    successCallback.run();
                }
            } catch (Exception e) {
                Log.e(TAG, "删除过期数据异常", e);
                if (errorCallback != null) {
                    errorCallback.accept(e.getMessage());
                }
            }
        });
    }
} 